﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Luminji.Core.Safe
{
    public sealed class MD5Helper
    {
        public static string GetMd5Hash(string input)
        {
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                return BitConverter.ToString(
                    md5.ComputeHash(UTF8Encoding.Default.GetBytes(input))).Replace("-", "");
            }
        }

        public static bool VerifyMd5Hash(string input, string hash)
        {
            string hashOfInput = GetMd5Hash(input);
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            return comparer.Compare(hashOfInput, hash) == 0 ? true : false;
        }

        /// <summary>
        /// <code>
        ///    string fileHash = GetFileHash(@"C:\temp.txt");
        ///    Console.WriteLine("文件MD5-HASH值为：{0}", fileHash);
        /// </code>
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileHash(string filePath)
        {
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            using (FileStream fs 
                = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "");
            }
        }

        /// <summary>
        /// provide a default salt in function
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMd5HashMoreSafe(string input)
        {
            string hashKey = "Aa1@#$,.Klj+{>.45oP";
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                string hashCode 
                    = BitConverter.ToString(
                        md5.ComputeHash(UTF8Encoding.Default.GetBytes(input))).Replace("-", "") 
                        + BitConverter.ToString(
                            md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashKey))).Replace("-", "");
                return BitConverter.ToString(
                    md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashCode))).Replace("-", "");
            }
        }

        public static string GetMd5HashMoreSafe(string input, string salt)
        {
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                return BitConverter.ToString(
                    md5.ComputeHash(UTF8Encoding.Default.GetBytes(input + salt))).Replace("-", "");
            }

        }
    }
}
